import type { DictValue, User } from '@/types'

export default defineStore('dict', () => {
  const dict = reactive({
    global: {} as Record<string, DictValue>,
    page: {} as Record<string, DictValue>,
  })

  function get(key: string, defaultValue: DictValue = []) {
    return dict.page[key] || dict.global[key] || defaultValue
  }

  function getName(key: string, id: number | string | number[] | string[] | undefined | null, defaultValue = '') {
    if (id === undefined || id === null) return defaultValue

    const list = Array.isArray(id) ? id.map((it) => String(it)) : [String(id)]
    return get(key)
      .filter((it) => list.includes(String(it.id)))
      .map((it) => it.name).join('')
      || defaultValue
  }

  const set = (key: string, value: DictValue) => {
    dict.page[key] = value
  }

  const setGlobal = (key: string, value: DictValue) => {
    dict.global[key] = value
  }

  const del = (key: string) => {
    delete dict.page[key]
  }

  const clean = () => {
    dict.page = {}
  }

  function has(key: string) {
    return dict.page[key] !== undefined || dict.global[key] !== undefined
  }

  const resolve = (data: Record<string, any>, keys: (string | [string, string])[], global = false) => {
    if (!data) {
      return
    }
    const target = global ? dict.global : dict.page
    for (const k of keys) {
      const key = Array.isArray(k) ? k[0] : k
      const value = data[Array.isArray(k) ? k[1] : k]
      if (Array.isArray(value)) {
        target[key] = value
      } else if (typeof value === 'string' && value.startsWith('[') && value.endsWith(']')) {
        target[key] = JSON.parse(value)
      }
      if (key === 'user' && target.user?.length && !target.user[0].id) {
        target[key] = (target[key] as unknown as User[]).map((it) => ({
          id: it.userId,
          name: it.nickName || it.userName,
        }))
      }
    }
  }

  setGlobal('gender', [
    { id: 0, name: '男' },
    { id: 1, name: '女' },
  ])

  return {
    get,
    getName,
    set,
    del,
    clean,
    resolve,
    has,
    setGlobal,
  }
})
